package com.binvshe.binvshe.app.home.adapter;

import android.content.Context;
import android.graphics.Color;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.binvshe.binvshe.R;
import com.binvshe.binvshe.account.Account;
import com.binvshe.binvshe.common.image.IML;
import com.binvshe.binvshe.entity.HomeEntity;
import com.binvshe.binvshe.mine.usercenter.UserCenterActivity;
import com.binvshe.binvshe.opus.OpusDetailsNewAcitvity;
import com.binvshe.binvshe.organization.entity.OpusListEntity;
import com.binvshe.binvshe.organization.tag.TagBean;
import com.pachong.android.baseuicomponent.adapter.RecyclerViewBaseAdapter;
import com.pachong.android.frameworkbase.utils.DateTimeUtil;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import java.util.Date;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import de.hdodenhof.circleimageview.CircleImageView;

import static com.binvshe.binvshe.app.home.adapter.MediaType.IMAGE;
import static com.binvshe.binvshe.app.home.adapter.MediaType.LONG_STORY;
import static com.binvshe.binvshe.app.home.adapter.MediaType.SHORT_STORY;
import static com.binvshe.binvshe.app.home.adapter.MediaType.TEXT;
import static com.binvshe.binvshe.app.home.adapter.MediaType.VIDEO;
import static com.binvshe.binvshe.common.image.IML.load;
import static com.umeng.analytics.a.p;

/**
 * Created by Zoi.
 * E-mail：KyluZoi@gmail.com
 * 2017/1/18
 */

public class HomeAdapter extends RecyclerViewBaseAdapter<HomeEntity> {

    private static final int IMAGE_VIEW_TYPE = 850;
    private static final int TEXT_VIEW_TYPE = 851;
    private static final int VIDEO_VIEW_TYPE = 852;


    public HomeAdapter(Context con) {
        super(con);
    }

    @Override
    public RecyclerView.ViewHolder onCreateHolder(ViewGroup parent, int viewType) {
        switch (viewType) {
            case IMAGE_VIEW_TYPE:
                return new ImageHolder(setAdapterViewItem(parent, R.layout.item_home_content));
            case TEXT_VIEW_TYPE:
                return new TextHolder(setAdapterViewItem(parent, R.layout.item_home_story));
            case VIDEO_VIEW_TYPE:
                return new VideoHolder(setAdapterViewItem(parent, R.layout.item_home_video));
        }
        return null;
    }


    //返回显示类型
    @Override
    public int getItemViewType(int position) {
        int type = super.getItemViewType(position);
        if (type == ITEM_VIEW_TYPE_ITEM) {
            switch (hasHeaderView() ? getData().get(position-1).getMedia_type() : getData().get(position).getMedia_type())//获得显示类型
            {
                case IMAGE:
                    return IMAGE_VIEW_TYPE;
                case TEXT:
                case SHORT_STORY:
                case LONG_STORY:
                    return TEXT_VIEW_TYPE;
                case VIDEO:
                    return VIDEO_VIEW_TYPE;
            }

        }
        return type;
    }

    @Override
    public void onBindHolder(RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof ImageHolder) {
            ((ImageHolder) holder).setData(getData().get(position));
        } else if (holder instanceof TextHolder) {
            ((TextHolder) holder).setData(getData().get(position));
        } else {
            ((VideoHolder) holder).setData(getData().get(position));
        }

        setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                   @Override
                                   public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                    OpusDetailActivity.start(getContext(), getData().get(position).getId());  //跳转到下级页面
                                       OpusDetailsNewAcitvity.start(getContext(), getData().get(position).getId());
                                   }
                               }

        );

    }


    private void setText(TextView view, String content) {
        if (TextUtils.isEmpty(content)) {
            return;
        }
        view.setText(content);
    }

    /**
     * 得到 tag 的Adapter
     */
    private TagAdapter getTagAdapter(final List<TagBean> tagDatas) {
        TagAdapter adapter = new TagAdapter<TagBean>(tagDatas) {
            @Override
            public int getCount() {
                return tagDatas.size() < 6 ? tagDatas.size() : 5;
            }

            @Override
            public View getView(FlowLayout parent, int position, TagBean o) {
                View view = ((LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.item_tag, parent, false);
                TextView tvTagDel = (TextView) view.findViewById(R.id.tvTagDel);
                TextView tvTag = (TextView) view.findViewById(R.id.tvTag);
                o.setPositon(position);
                tvTag.setText(o.getTagContent());
                o.getTagBackGround(tvTag);
                tvTag.setTextColor(o.getTagTextColor());
                return view;
            }
        };
        return adapter;
    }


    /**
     * 获取图片高宽，屏幕高度减去padding 4等分
     *
     * @return
     */
    private int getImageSize() {
        float parentSpace = getContext().getResources().getDimensionPixelOffset(R.dimen.space_lv5) * 2;
        float subSpace = getContext().getResources().getDimensionPixelOffset(R.dimen.space_lv1) * 4;
        WindowManager wm = (WindowManager) getContext()
                .getSystemService(Context.WINDOW_SERVICE);
        int width = (int) (wm.getDefaultDisplay().getWidth() - (parentSpace + subSpace));
        return width / 4;
    }


    /**
     * 图文holder
     */
    class ImageHolder extends RecyclerView.ViewHolder {
        @Bind(R.id.civUserHead)
        CircleImageView mCivUserHead;
        @Bind(R.id.tvUserName)
        TextView mTvUserName;
        @Bind(R.id.tvUserOrg)
        TextView mTvUserOrg;
        @Bind(R.id.btnMore)
        ImageView mBtnMore;
        @Bind(R.id.tvContentTitle)
        TextView mTvContentTitle;
        @Bind(R.id.tvContentDesc)
        TextView mTvContentDesc;
        @Bind(R.id.lnlytImage)
        LinearLayout mLnlytImage;
        @Bind(R.id.tflytContentTag)
        TagFlowLayout mTflytContentTag;
        @Bind(R.id.tvOpusCreateTime)
        TextView mTvOpusCreateTime;
        @Bind(R.id.tvZanNum)
        TextView mTvZanNum;
        @Bind(R.id.tvCommentNum)
        TextView mTvCommentNum;
        @Bind(R.id.hotLytText)
        TextView hotLytText;


        public ImageHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }

        public void setData(final HomeEntity data) {
            mLnlytImage.removeAllViews();
            mTflytContentTag.removeAllViews();
            //<code> 加载image信息 </code>
            int i = 0;//foreach没有索引，自己创建索引
            for (OpusListEntity.ImagesEntity imagesEntity : data.getImages()) {
                if (i < 4) {
                    if(i==data.getImages().size()-1|| i == 3){
                        RelativeLayout  relativeLayout = new RelativeLayout(getContext());
                        RelativeLayout.LayoutParams rl = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
                                RelativeLayout.LayoutParams.MATCH_PARENT);

                        RelativeLayout.LayoutParams layoutParams1 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
                        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(getImageSize(), getImageSize());
                        layoutParams.setMargins(0, 0, getContext().getResources().getDimensionPixelOffset(R.dimen.space_lv1), 0);
                        relativeLayout.setLayoutParams(layoutParams);
                        ImageView imageView = new ImageView(getContext());
                        TextView textView = new TextView(getContext());
                        imageView.setLayoutParams(rl);
                        textView.setLayoutParams(layoutParams1);
                        layoutParams1.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
                        layoutParams1.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
                        textView.setTextColor(Color.WHITE);
                        relativeLayout.addView(imageView);
                        relativeLayout.addView(textView);
                        IML.load(getContext(), imageView, imagesEntity.getUrl());
                        textView.setText("共"+data.getImages().size()+"张");
                        textView.setTextSize(10);
                        textView.setBackgroundResource(R.drawable.home_list_shape);
                        mLnlytImage.addView(relativeLayout, layoutParams);

                    }else{
                        ImageView imageView = new ImageView(getContext());
                        TextView textView = new TextView(getContext());
                        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(getImageSize(), getImageSize());
                        layoutParams.setMargins(0, 0, getContext().getResources().getDimensionPixelOffset(R.dimen.space_lv1), 0);
                        imageView.setLayoutParams(layoutParams);
                        IML.load(getContext(), imageView, imagesEntity.getUrl());
                        hotLytText.setText(data.getImages().size()+"");
                        mLnlytImage.addView(imageView,layoutParams );
                    }

                } else {
                    break;
                }
                i++;
            }
            //<code>加载标签信息</code>
            TagAdapter adaptet = getTagAdapter(data.getTags());
            mTflytContentTag.setAdapter(adaptet);
            adaptet.notifyDataChanged();
            //<code>加载用户以及内容信息</code>
            Account userEntity = data.getUser();
            load(getContext(), mCivUserHead, userEntity.getPortrait());
            mCivUserHead.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    UserCenterActivity.start(getContext(), data.getUser().getUserId());
                }
            });

            mTvUserName.setText(userEntity.getNickName());
//        if (data.getClub() != null) {//作品所在社团
//            setText(mholder.mTvUserOrg, data.getClub().getName());
//        }
            if (userEntity.getClub() != null) {//用户所在社团
                setText(mTvUserOrg, userEntity.getClub().getName());
            } else {
                setText(mTvUserOrg, "");
            }
            setText(mTvContentTitle, data.getTitle());
            setText(mTvContentDesc, data.getContent());
            String date = DateTimeUtil.getDateStr(new Date(data.getCreate_time()));
            setText(mTvOpusCreateTime, date);
            setText(mTvCommentNum, data.getComment_count() + "");
            setText(mTvZanNum, data.getLike_count() + "");
            /**
             if (getJBulderType() != null) {
             mholder.mBtnMore.setVisibility(View.VISIBLE);
             mholder.mBtnMore.setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View v) {
            switch (getJBulderType()) {
            case DELETE:
            buildJump(v, new JumpWindowView.OnFlipClickListener() {
            @Override public void onItemClick(int position) {
            deleteArticle(data.getId());
            }

            @Override public void dismiss() {

            }
            });
            break;
            case SHARE:
            buildJump(v, new JumpWindowView.OnFlipClickListener() {
            @Override public void onItemClick(int position) {
            recommend(data.getId());
            }

            @Override public void dismiss() {

            }
            });
            break;
            }
            }
            });
             } else {
             mholder.mBtnMore.setVisibility(View.GONE);
             }
             **/

        }
    }

    /**
     * 小说holder
     */
    class TextHolder extends RecyclerView.ViewHolder {


        @Bind(R.id.ivCover)
        ImageView mIvCover;
        @Bind(R.id.tvTitle)
        TextView mTvTitle;
        @Bind(R.id.tvDesc)
        TextView mTvDesc;
        @Bind(R.id.tvUpdateContent)
        TextView mTvUpdateContent;
        @Bind(R.id.tvAuthor)
        TextView mTvAuthor;
        @Bind(R.id.tvStatus)
        TextView mTvStatus;
        @Bind(R.id.tflytContentTag)
        TagFlowLayout mTflytContentTag;
        @Bind(R.id.tvCover)
        TextView tvCover;

        public TextHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }

        public void setData(HomeEntity homeEntity) {
            load(getContext(), mIvCover, homeEntity.getCover_image());
            mTvTitle.setText(homeEntity.getTitle());
            mTvDesc.setText("简介 " + homeEntity.getDescription());
            mTvUpdateContent.setText(TextUtils.isEmpty(homeEntity.getContent()) ? ""
                    : "最新更新:" + homeEntity.getContent());
            mTvAuthor.setText(homeEntity.getUser().getNickName());
            if (homeEntity.getFlag()) {
                mTvStatus.setText("已完结");
                mTvStatus.setTextColor(Color.parseColor("#666666"));
                tvCover.setBackgroundResource(R.drawable.home_list_shape);
                tvCover.setTextSize(10);
                tvCover.setText("已完结");
            } else {
                mTvStatus.setText("连载中");
                mTvStatus.setTextColor(Color.parseColor("#3CE660"));
                tvCover.setBackgroundResource(R.drawable.home_list_shape);
                tvCover.setTextSize(10);
                tvCover.setText("连载中");
            }
            //<code>加载标签信息</code>
            TagAdapter adaptet = getTagAdapter(homeEntity.getTags());
            mTflytContentTag.setAdapter(adaptet);
            adaptet.notifyDataChanged();
        }
    }

    /**
     * 视频holder
     */
    class VideoHolder extends RecyclerView.ViewHolder {
        @Bind(R.id.civUserHead)
        CircleImageView mCivUserHead;
        @Bind(R.id.tvUserName)
        TextView mTvUserName;
        @Bind(R.id.tvUserOrg)
        TextView mTvUserOrg;
        @Bind(R.id.btnMore)
        ImageView mBtnMore;
        @Bind(R.id.tvContentDesc)
        TextView mTvContentDesc;
        @Bind(R.id.ivCover)
        ImageView mIvCover;
        @Bind(R.id.tvOpusCreateTime)
        TextView mTvOpusCreateTime;
        @Bind(R.id.tvZanNum)
        TextView mTvZanNum;
        @Bind(R.id.tvCommentNum)
        TextView mTvCommentNum;

        public VideoHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }

        public void setData(HomeEntity homeEntity) {

        }
    }
}
